#pragma once
#include <cassert>
#include <iostream>
#include <vector>
#include <semaphore.h>
static const int gcap = 5;
template <class T>
class RingQueue
{
private:
    void P(sem_t &sem)
    {
        int n = sem_wait(&sem);
        assert(n == 0);
        (void)n;
    }
    void V(sem_t &sem)
    {
        int n = sem_post(&sem);
        assert(n == 0);
        (void)n;
    }

public:
    RingQueue(const int &cap = gcap)
        : _queue(cap), _cap(cap)
    {
        int n = sem_init(&_spacesem, 0, _cap);
        assert(n == 0);
        n = sem_init(&_datasem, 0, 0);
        assert(n == 0);
        (void)n;
        _productorstep = _consumerstep = 0;
    }
    void push(const T &in)
    {
        P(_spacesem);
        _queue[_productorstep++] = in;
        _productorstep %= _cap;
        V(_datasem);
    }
    void pop(T *out)
    {
        P(_datasem);
        *out = _queue[_consumerstep++];
        _consumerstep %= _cap;
        V(_spacesem);
    }
    ~RingQueue()
    {
        sem_destroy(&_spacesem);
        sem_destroy(&_datasem);
    }

private:
    std::vector<T> _queue;
    int _cap;
    int _productorstep;
    int _consumerstep;
    sem_t _spacesem;
    sem_t _datasem;
};